package com.atguigu.mall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
public class RedisCacheConfig {


    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        CacheProperties.Redis redisConfig = cacheProperties.getRedis();

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()));
        if (redisConfig.getTimeToLive() != null) {
            config = config.entryTtl(redisConfig.getTimeToLive());
        }
            if (redisConfig.getKeyPrefix() != null) {
                config = config.prefixCacheNameWith(redisConfig.getKeyPrefix());
            }
            if (!redisConfig.isCacheNullValues()) {
                config = config.disableCachingNullValues();
            }
            if (!redisConfig.isUseKeyPrefix()) {
                config = config.disableKeyPrefix();
            }
            return config;
        }
}
